<?php


/*
 * Created on Mar 11, 2011
 * Project	: ecbackend
 * File		: util_helper.php
 * Todo		: TODO
 * Author 	: Nguyen Ngoc Thach
 * Email 	: ngocthach792002@yahoo.com
 */

class UtilHelp {

	function get_user_id_subdomain()
	{		
		$subdomain='';
		// GET SUBDOMAIN NAME
		$Parts = explode('.', $_SERVER['HTTP_HOST']);
		if($Parts[0]!='www' && $Parts[0]!='bma-academy')
		{
			$subdomain=$Parts[0];
		}
		if($Parts[0]=='www' && $Parts[1]!='bma-academy')
		{
			$subdomain=$Parts[1];
		}
		// GET USER ID OF SUBDOMAIN
		if($subdomain!='')
		{
			$CI = & get_instance();
			$query = $CI->db->query("SELECT c.id_company FROM company c INNER JOIN company_user cu ON cu.id_company = c.id_company where sub_domain LIKE '".$subdomain."'");
			if ($query->num_rows() > 0)
			{
			   $row = $query->row();
			   return $row->id_company;
			} 
			else
			{
				return 1;
			}	
		}
		else
		{
			return 1;
		}
	}
    
    function getTemplateFolder($user_id) {
        $CI = & get_instance();
        $sql = "SELECT folder FROM template t INNER JOIN client_template c ON t.template_id = c.template_id WHERE user_id = $user_id";
        $query = $CI->db->query($sql);
        $row = $query->row();
        if (isset($row->folder)) {
            return $row->folder;
        }
        else {
            $sql = "SELECT folder FROM template WHERE published = 1 LIMIT 1";
            $query = $CI->db->query($sql);
            $row = $query->row();
            return $row->folder;
        }
    }
    
	function get_companyid($userid){		
	
		$CI = & get_instance();
		$query = $CI->db->query("SELECT id_company FROM company where user_id =".$userid);

		if ($query->num_rows() > 0)
		{
		   $row = $query->row();
		   return $row->id_company;
		} 	
	}
	function isLogin() {
		$CI = & get_instance();
		if (!$CI->session->userdata('logged_in')) {
			return false;
		}
		return true;
	}

	function checkLogin() {
		$CI = & get_instance();
		if (!$CI->session->userdata('logged_in')) {
			redirect('/admin');
		}
	}

	
	function getUserInfo() {
		$usersInfor = new stdClass();
		if (!UtilHelp :: isLogin()) {
			return $usersInfor;
		}
		$CI = & get_instance();
		
		return $usersInfor;
	}
	function defaultLanguageID($default = 1) // ID of default language
	{
		$CI 	=& get_instance();
		
        $query = "SELECT lang_id FROM languages WHERE `default`=1";
		$output = $default;
		$result = $this->db->query($query);		
		if ($result->num_rows() > 0) {
			$row=$result->row(); 		
			$output =$row->lang_id;
		}					                 
		return $output;
	}
	function initialLanguage($section = false){
		$CI 	=& get_instance();
		$df_lang = UtilHelp::mainLang();
		$df_langID = UtilHelp::defaultLanguageID();
		if(!$CI->session->userdata('lang')){
			$CI->session->set_userdata('lang',$df_lang);
			$CI->session->set_userdata('langID',$df_langID);
		}
        
		$language = '';
		if($CI->session->userdata('lang') == 'en'){			
			$CI->db->query("SET lc_time_names = 'en_GB';");
			$language = 'english';
		}
		
		if($CI->session->userdata('lang') == 'vi'){
			$CI->db->query("SET lc_time_names = 'vi_VN'");
			$language = 'vi';		
		}
		if($section){
			$CI->lang->load($section, $language);
		}
	}
	
	function currentLang(){
		$df_lang = UtilHelp::mainLang();
		$CI 	=& get_instance();
		if(!$CI->session->userdata('lang')){
			return $df_lang;
		}		
		return $CI->session->userdata('lang');
	}
	
	function mainLang(){		
		$CI 	=& get_instance();
		$lang = $this->uri->segment(1);
		$mainLang = '';
		switch($lang){
			case 'en': $mainLang = 'english'; break;				
			case 'vi': $mainLang = 'vi'; break;
			default: $mainLang = $this->config->item('language'); break;				
		}
		return $mainLang;
	}
    
    function getLang($page) {        
        $mainLang = UtilHelp::mainLang() ;
        require_once ($this->config->item('site_root').'application/language/'.$mainLang.'/common_lang.php');
        require_once ($this->config->item('site_root').'application/language/'.$mainLang.'/'.$page.'_lang.php');
    }
	
	function checkLength($text, $maxchars = 0, $def = null) {
		global $cfg_mamblog;

		$newtext = UtilHelp::safeStrip($text);
		$strlen = strlen($newtext);

		if ($maxchars > 0 && $maxchars < $strlen) {
			$text = substr($newtext, 0, $maxchars);

			$text1 = substr($text, 0, strripos($text, ' ', 0));
			if (strlen($text1) == 0) {
				$text1 = $text;
			}
			if ($def == 'none_ext') {
				$text = $text1;
			} else {
				$text = $text1 . "...";
			}

		} else {
			$text = UtilHelp::safeStrip($text);
		}

		return $text;
	}

	/**
	 * Strips tags without removing possible white space between words.
	 *
	 * @param string String to strip tags from.
	 */
	function safeStrip($text) {

		$text = preg_replace('/</', ' <', $text);
		$text = preg_replace('/>/', '> ', $text);
		$desc = strip_tags($text);
		$desc = preg_replace('/  /', ' ', $desc);

		return $desc;
	}

	/**
	 * 
	 */
	function pagination($url, $total, $perPage, $crrPage = '', $uri_segment = '') {
		$CI = & get_instance();

		$config = array();
        $config['base_url'] = $url;
        $config['total_rows'] = $total;
        $config['per_page'] = $perPage;
        $config['prev_link'] = 'Prev';
        $config['next_link'] = 'Next';
        
        $config['prev_tag_close'] = '</li>';
        $config['next_tag_open'] = '<li style="padding-left:15px">';
        
        $config['num_tag_open'] = '';
        $config['num_tag_close'] = '&nbsp;&nbsp;|&nbsp;&nbsp;</li>';
        $config['cur_tag_open'] = '<strong>';
        $config['cur_tag_close'] = '&nbsp;&nbsp;|&nbsp;&nbsp;</strong>';
        if ($crrPage != '') {
            $config['cur_page'] = $crrPage;    
        }
        if ($uri_segment != '') {
            $config['uri_segment'] = $uri_segment;
        }

		return $config;
	}

	function convert_html_to_asscii($str) {
		$asscii = array (
			'&lt;',
			'&gt;'
		);
		$char = array (
			'<',
			'>'
		);
		$str = str_ireplace($char, $asscii, $str);
		return $str;
	}

    function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
    }
    
	function getValue(& $value) {
		if (isset ($value)) {
			return $value;
		} else {
			return null;
		}
	}

			
	/**
	 * Function to convert array to integer values
	 * @param array
	 * @param int A default value to assign if $array is not an array
	 * @return array
	 */
	function ArrayToInts(& $array, $default = null) {
		if (is_array($array)) {
			foreach ($array as $key => $value) {
				$array[$key] = (int) $value;
			}
		} else {
			if (is_null($default)) {
				$array = array ();
				return array (); // Kept for backwards compatibility
			} else {
				$array = array (
					(int) $default
				);
				return array (
					$default
				); // Kept for backwards compatibility
			}
		}
	}

	function convertDateFormat($data, $format='dd/mm/YYYY'){
		$date = '';
		$month = '';
		$year = '';
		switch($format){
			case 'dd/mm/YYYY':
				list($date, $month, $year) = explode('/',$data);
				break;
			case 'dd-mm-YYYY':
				list($date, $month, $year) = explode('-',$data);
				break;
			case 'YYYY/mm/dd':
				list($year, $month, $date) = explode('/',$data);
				break;
			case 'YYYY-mm-dd':
				list($year, $month, $date) = explode('-',$data);
				break;
		}
		
		return $year.'-'.$month.'-'.$date;
	}
	
	function makeData($data_nl='', $data_en=''){
		$object = new stdClass();
		$object->nl = $data_nl;
		$object->en = $data_en;
		return json_encode($object);
	}
	
	/*
	 * @type = 0 : print data of current language
	 * @type = 1 : print data as object with all language
	 */
	function getData($object, $return_type = 0){
        $CI 	=& get_instance();
		$data = json_decode($object);
		if(is_null($data)) {
            $data->nl = $object;
            $data->en = $object;
		}
		if($return_type == 0) { //return as current language		
            $current_lang = UtilHelp::currentLang();
            $df_lang = UtilHelp::mainLang();
            $return = UtilHelp::getValue($data->$current_lang);             
            //return  $return ? $return : UtilHelp::getValue($data->$df_lang);  	             		            		
			return  $return ? $return : '';  	             		            		
		}
		return $data;
	}
	
	function createcode($data, $number = 5){		
		if(is_string($data)){
			$count = count($data);
			if($count > $number)return $data;
			for($i=0; $i< ($number - $count); $i++){
				$data = '0'.$data;
			}
			return $data;
		}
		return 0;
	}
	function createURLTitle($id, $title_string) {
        return $id.'-'.url_title($title_string);
    }
    
    function getIDURLTitle($url_title) {
        $num = strpos($url_title, '-');
        if ($num) {
            return substr($url_title, 0, $num);
        }
        else {
            if (is_numeric($url_title)) {
                return $url_title;
            }
        }
        return 0;
    }
	function linkTemp(){
		$CI 	=& get_instance();
		return $CI->config->item('base_url');
	}
	
	function builURLImage($image_path){
		$CI 	=& get_instance();
		return $CI->config->item('link-assets').$image_path;
	}
	function get_EnglistData($json)
	{
		$obj = json_decode($json);
		return $obj->{'en'};
	}
	function PlanningDateDetail($id = 0){		
		$CI = & get_instance();
		$query = "SELECT DATE_FORMAT(start_date,'%W %d-%m-%Y') as start_date
				FROM ptf_vca_planning 
				WHERE id_vca_planning=".$id." and closed =1";
		$output = '';
		$result = $this->db->query($query);		
		if ($result->num_rows() > 0) {
			$row=$result->row(); 		
			$output =$row->start_date;
		}					                 
		return $output;
	}
	function PlanningStartDate($id = 0){		
		$CI = & get_instance();
		$query = "SELECT DATE_FORMAT(start_date,'%Y-%m-%d') as start_date
				FROM ptf_vca_planning 
				WHERE id_vca_planning=".$id." and closed =1";
		$output = '';
		$result = $this->db->query($query);		
		if ($result->num_rows() > 0) {
			$row=$result->row(); 		
			$output =$row->start_date;
		}					                 
		return $output;
	}
	function setHeader($title='', $description='', $keywords='', $author='') {
        $CI =& get_instance();
        $str_header  = '
        <title>..: '.$title.($title != ''?' : ':'').$CI->config->item('header_title').' :..</title>
        <meta name="title" content="'.$title.($title != ''?' : ':'').$CI->config->item('header_title').'" />
        <meta name="author" content="'.$author.($author != ''?', ':'').$CI->config->item('header_author').'" />
        <meta name="description" content="'.$description.($description != ''?', ':'').$CI->config->item('header_description').'" />
        <meta name="keywords" content="'.$keywords.($keywords != ''?', ':'').$CI->config->item('header_keywords').'" />
        ';
        return $str_header;
    }
}

class MailHelp{
	function config(){
		$mail_confg = array();
		/*$mail_confg['protocol'] 	= $this->config->item('protocol');
		$mail_confg['smtp_host'] 	= $this->config->item('smtp_host');
		$mail_confg['smtp_user'] 	= $this->config->item('smtp_user');
		$mail_confg['smtp_pass']	= $this->config->item('smtp_pass');
		$mail_confg['smtp_port'] 	= $this->config->item('smtp_port');
		$mail_confg['mailpath'] 	= $this->config->item('mailpath');*/
		$mail_confg['wordwrap'] 	= $this->config->item('wordwrap');
		$mail_confg['mailtype'] 	= $this->config->item('mailtype');
		$mail_confg['charset'] 	= $this->config->item('charset');
		$mail_confg['newline'] 	= $this->config->item('newline');
		return $mail_confg;
	}
	
    function loadEmailTemplateEN($data) {
        ob_start();
        ?>
        <style type="text/css">
            body {
            	margin-left: 0px;
            	margin-top: 0px;
            	margin-right: 0px;
            	margin-bottom: 0px;
            	font-family:"Arial", Helvetica, sans-serif;
            	color:#000;
            	font-size:13px;
            	line-height:18px
            }
            a{
            	color:#0051a4;
            	text-decoration:none;	
            }
            a:hover{
            	color:#0051a4;
            	text-decoration:underline;	
            }
        </style>

        <table width="600" border="0" align="center" cellpadding="0" cellspacing="0">
            <tr>
                <td height="60" style="background:#F2F2F2; padding:10px">
                	<table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                            <td width="24%"><img src="<?php echo base_url(); ?>assets/images/logo_email.png" width="50" /></td>
                            <td width="76%" align="right" style="padding-left:10px; color:#06C; font-size:16px;"><?php echo $data->title; ?></td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td style="padding:10px; border:1px solid #e4e4e4">
                	<table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                            <td style="padding:10px 0 40px 0">
                                <?php
                                    echo $data->body;
                                ?>
        						Kind regards,
                            </td>
                        </tr>
                        <tr>
                            <td valign="top" style="background:url(<?php echo base_url(); ?>assets/images/bg-body.jpg); border-top:1px dotted #acacac; padding-top:10px">
                            	<table width="100%" border="0" cellspacing="0" cellpadding="0">
                                    <tr>
                                        <td>
                                        	<b>BMA Academy</b><br />
                                Rembrandtweg 257 | 2981 CZ Ridderkerk<br />
                                Telephone: 0180 - 420199<br />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="42"><a href="http://www.bma.nl">www.bma.nl</a> &nbsp;|&nbsp; <a href="http://www.easycursus.nl">www.easycursus.nl</a> &nbsp;|&nbsp; <a href="http://www.dgs-arbo.nl">www.dgs-arbo.nl</a> &nbsp;|&nbsp; <a href="http://www.pontifex.nl">www.pontifex.nl</a></td>
                                    </tr>
                                    <tr>
                                        <td style="color:#777777">
                                        	This message (including any attachments) may be privileged or confidential. If you have received it by mistake, please notify the sender by return e-mail and delete this message from your system. Any unauthorised use or dissemination of this message in whole or in part is strictly prohibited.
                                        </td>
                                    </tr>
                                </table>
                        	</td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
        
        <?php    
        $strEmail = ob_get_contents();
        ob_end_clean();
        return $strEmail;
    }
    
    function loadEmailTemplateNL($data) {
        ob_start();
        ?>
        <style type="text/css">
            body {
            	margin-left: 0px;
            	margin-top: 0px;
            	margin-right: 0px;
            	margin-bottom: 0px;
            	font-family:"Arial", Helvetica, sans-serif;
            	color:#000;
            	font-size:13px;
            	line-height:18px
            }
            a{
            	color:#0051a4;
            	text-decoration:none;	
            }
            a:hover{
            	color:#0051a4;
            	text-decoration:underline;	
            }
        </style>

        <table width="600" border="0" align="center" cellpadding="0" cellspacing="0">
            <tr>
                 <td height="60" style="background:#F2F2F2; padding:10px">
                	<table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                            <td width="24%"><img src="<?php echo base_url(); ?>assets/images/logo_email.png" width="50" /></td>
                            <td width="76%" align="right" style="padding-left:10px; color:#06C; font-size:16px;"><?php echo $data->title; ?></td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td style="padding:10px; border:1px solid #e4e4e4">
                	<table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                            <td style="padding:10px 0 40px 0">
                                <?php
                                    echo $data->body;
                                ?>
        						Met vriendelijke groet,
                            </td>
                        </tr>
                        <tr>
                            <td valign="top" style="background:url(<?php echo base_url(); ?>assets/images/bg-body.jpg); border-top:1px dotted #acacac; padding-top:10px">
                            	<table width="100%" border="0" cellspacing="0" cellpadding="0">
                                    <tr>
                                        <td>
                                    		<b>BMA Academy</b><br />
                            				Rembrandtweg 257 | 2981 CZ Ridderkerk<br />
                            				Telefoon: 0180 - 420199<br />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="42"><a href="http://www.bma.nl">www.bma.nl</a> &nbsp;|&nbsp; <a href="http://www.easycursus.nl">www.easycursus.nl</a> &nbsp;|&nbsp; <a href="http://www.dgs-arbo.nl">www.dgs-arbo.nl</a> &nbsp;|&nbsp; <a href="http://www.pontifex.nl">www.pontifex.nl</a></td>
                                    </tr>
                                    <tr>
                                        <td style="color:#777777">
                                        	De inhoud van dit e-mailbericht en van de eventueelmeegezondenbestanden is striktvertrouwelijk en uitsluitendbestemdvoor de geadresseerde. Gebruik van dezeinhoud door anderenzondertoestemming van de afzender of de geadresseerde is onrechtmatig.
                                        </td>
                                    </tr>
                                </table>
                        	</td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
        
        <?php    
        $strEmail = ob_get_contents();
        ob_end_clean();
        return $strEmail;        
    }
    
	function loadEmailTemplate($data, $lang='en'){
		$strEmail = '';
        if ($lang == 'en') {
            $strEmail = MailHelp::loadEmailTemplateEN($data);
        }
        else {
            $strEmail = MailHelp::loadEmailTemplateNL($data);
        }
        return $strEmail;
	}

}

class FTPHelp{
	
	private function initFTPSession(){
		$CI 	=& get_instance();
		$CI->load->library('ftp');
		$config	= array();
		$config['hostname'] 	= $CI->config->item('ftp-hostname');
		$config['username'] 	= $CI->config->item('ftp-username');
		$config['password'] 	= $CI->config->item('ftp-password');
		$config['port'] 		= $CI->config->item('ftp-port');
		$config['debug'] 		= $CI->config->item('ftp-debug');		
		$CI->ftp->connect($config);	
	}
	
	function upload($path_from, $path_to){	
		$CI 	=& get_instance();	
		$class = new FTPHelp();
		$class->initFTPSession();						
		$this->ftp->upload($path_from, $CI->config->item('ftp-folder-assets').$path_to, 'auto', 0775);		
		$this->ftp->close(); 
	}
	
	function delete($path_file){		
		$CI 	=& get_instance();
        $class = new FTPHelp();
		$class->initFTPSession();								
		$this->ftp->delete_file($CI->config->item('ftp-folder-assets').$path_file);		
		$this->ftp->close(); 
	}
	 
}

class SubsiteHelper {
    function getLogo($user_id) {
        $CI 	=& get_instance();
        $query = $CI->db->query('SELECT * FROM client_template WHERE user_id = '.$user_id);
        $row = $query->row();
        return $row->logo;
    }
    
    function getBanner($user_id) {
        $CI 	=& get_instance();
        $query = $CI->db->query('SELECT * FROM banner_image WHERE user_id = '.$user_id);
        $result = $query->result();
        $num = count($result);
        if ($num == 1) return $result[0]->image;
        if ($num < 1) return '';
        $rand_num = rand(1, $num);
        return $result[$rand_num]->image;
    }
}